package se.rende.myrss.data;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import se.rende.myrss.data.ChannelParser.ChannelItem;
import se.rende.myrss.data.ChannelParser.ChannelParseListener;
import se.rende.myrss.data.ChannelUtil.Channel;
import se.rende.myrss.data.ChannelUtil.ChannelInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class ChannelToDbLoader {
	private MyRSSDataHelper data;

	public ChannelToDbLoader(MyRSSDataHelper data) {
		this.data = data;
	}

	public void load(String baseUrl, String channelId) {
		try {
			SQLiteDatabase db = data.getWritableDatabase();
			Log.d("ChannelToDbLoader", "load(" + baseUrl + ", " + channelId + ")");
			final ChannelInfo channelInfo = ChannelUtil.getChannelInfo(data, channelId);
			Log.d("ChannelToDbLoader", "channelInfo=" + channelInfo);
			StringBuilder args = new StringBuilder();
			final Map<String, Long> latestPubDateByChannel = getLatestPubDate(db);
			for (Channel channel : channelInfo.channels) {
				if (args.length() > 0) {
					args.append("&");
				}
				args.append("ch=" + channel.url);
				Long latestPubDate = latestPubDateByChannel.get(channel.id);
				if (latestPubDate == null) {
					latestPubDate = Long.valueOf(0L);
				}
				args.append("&since=" + URLEncoder.encode(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US).format(latestPubDate), "utf-8"));
			}
			
//			db.execSQL("delete from item");
			final SQLiteStatement statement = db.compileStatement(
					"insert into item (channel, title, description, link, pub_date, creator, seen, star)  values(?, ?, ?, ?, ?, ?, ?, ?)");
			ChannelParser channelParser = new ChannelParser();
			channelParser.setChannelParseListener(new ChannelParseListener() {
				@Override
				public void addItem(ChannelItem item) {
					String itemChannelId = channelInfo.getChannelBySourceTitle(item.sources, item.source).id;
					Long latestPubDate = latestPubDateByChannel.get(itemChannelId);
					if (item.pubDate > (latestPubDate != null ? latestPubDate : 0)) {
						Log.d("ChannelToDbLoader", "item.sources=" + item.sources + ", item.source=" + item.source + ", id=" + itemChannelId);
						statement.bindString(1, itemChannelId);
						statement.bindString(2, item.title);
						statement.bindString(3, item.description);
						statement.bindString(4, item.link);
						statement.bindLong(5, item.pubDate);
						statement.bindString(6, (item.creator == null ? "" : item.creator));
						statement.bindLong(7, 0);
						statement.bindLong(8, 0);
						statement.executeInsert();
					}
				}
			});
			channelParser.parse(baseUrl + "?" + args.toString());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Map<String, Long> getLatestPubDate(SQLiteDatabase db) {
		Map<String, Long> latestByChannel = new HashMap<String, Long>();
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select channel, max(pub_date) from item group by channel", new String[] {});
			if (cursor != null) {
				while (cursor.moveToNext()) {
					latestByChannel.put(cursor.getString(0), cursor.getLong(1));
				}
			}
		} finally {
			if (cursor != null) {
				cursor.close();			
			}
		}
		return latestByChannel;
	}

}
